<?php

namespace Module\Cms;

use Base\Contents;
use W3\Router;
use W3\Exception;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 处理分类
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Category extends Contents
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
		# 定义变量默认数据
        $this->parameter([

			# 设置主体
			'main' => 'category',
			
			# 分页大小
		    'pageSize' => 20,
			
			# 主题文件
            'themeFile' => 'category',
			
		], true);
	}

    public function execute()
    {
        $categorySelect = $this->db
            ->select()
			->from('table.metas')
            ->where('type = ?', 'category')
            ->limit(1);

        if (isset($this->request->mid)) {
            $categorySelect->where('mid = ?', $this->request->filter('int')->mid);
        }

        if (isset($this->request->alias)) {
            $categorySelect->where('alias = ?', $this->request->alias);
        }

        if (isset($this->request->directory)) {
            $directory = explode('/', $this->request->directory);
            $categorySelect->where('alias = ?', $directory[count($directory) - 1]);
        }
		
        $category = $categorySelect->fetch();
		$category && $category = $this->widget('Category\Rows')
		    ->get($category['mid']);
		
        if (empty($category)) {
			throw new Exception(__('分类不存在'), 404);
        }

        if (isset($directory) && $category && ($this->request->directory != implode('/', $category['directory']))) {
			throw new Exception(__('父级分类不存在'), 404);
        }

		/** 设置参数 */
		$this->request->setParams('mid', $category['mid']);

        /** 计算数目 */
		$total = $category['count'];
		$page = $this->request->get('page', 1);
		$pageSize = $this->parameter->pageSize;

        /** 设置分页 */
		$category = array_merge($category, [
            'alias'  =>  urlencode($category['alias']),
			'page'=>'%page%'
        ]);

		$pageUrl = Router::buildUrl('category_page', $category);

		$cids = $this->db->select('table.relate.cid')
		    ->from('table.relate')
		    ->where('table.relate.mid = ?', $category['mid'])
		    ->page($page, $pageSize)
		    ->get();

		if($cids){
            $select = $this->db
		    ->select()
		    ->from('table.contents')
			->where('table.contents.cid IN ('.implode(',', array_column($cids, 'cid')).')')
			->order('table.contents.cid', 'DESC')
			->get([$this, 'push']);
		}

		$this->parameter([
		
		    # 设置关键词
		    'keywords' => $category['name'],
			
			# 设置描述
		    'description' => $category['description'],
			
			# 设置标题
		    'title' => $category['name'],
		
		    # 设置缩略名
		    'alias' => $category['alias'],
			
			# 当前页数
			'page' => $page, 
			
			# 内容总数
			'total' => $total, 
			
			# 页面Url
			'pageUrl' => $pageUrl,
			
		]);
		
    }

}

